// 传入一个字符串返回的是一个正则表达式
const { pathToRegexp } = require("path-to-regexp")
const {ValidationError} = require("../customError")
const jwt = require("../jwtTool");
// 不需要验证的api
const needTokenApi = [
    { method: "POST", path: "/api/user/register" }, // 用户注册接口
    { method: "POST", path: "/api/admin" },
    { method: "POST", path: "/api/admin/register" },
    { method: "POST", path: "/api/user" }, // 用户登录接口
    { method: "GET", path: "/static/image/:id"}, // 静态资源
    { method: "GET", path: "/api/moveAbout"},
    { method: "GET", path: "/api/moveAbout/:id"},
]

module.exports = (req,res,next)=>{
    // /api/student/:id 和  /api/student/1771
    const apis = needTokenApi.filter(api => {
        const reg = pathToRegexp(api.path);
        return api.method === req.method && reg.test(req.path);
    })
    if (apis.length !== 0) {
        next();
        return;
    }

    const result = jwt.analysis(req);
    if (result) {
        // 有值的话就是登录了
        req.userInfo =result
        next()
    } else {
        // 如果没有登录
       throw new ValidationError("未登录或登录已过期,请重新登录");
    }
}
